<template>
  <div class="edit">
    <div class="info">
      基本信息
    </div>
    <div class="basic">
      <nut-form>
        <nut-form-item label="商品图片" required>
          <nut-uploader :url="uploadUrl" accept="image/*" maximum="5" multiple v-model:file-list="defaultFileList"
            @success="picSucc" @delete="picDel">
          </nut-uploader>
        </nut-form-item>
        <nut-form-item label="商品名称" required>
          <nut-input v-model="basicData.name" class="nut-input-text" placeholder="请输入商品名称" type="text" />
        </nut-form-item>
        <nut-form-item label="商品描述">
          <nut-input v-model="basicData.text" class="nut-input-text" placeholder="请输入商品描述" type="text" />
        </nut-form-item>
        <!-- <nut-form-item label="商品标签">
          <div class="flex-a flex-b">
            <picker mode="selector" :range="selector" @change="onChange">
              <view class="picker">
                {{ selectorChecked }}
                <TriangleDown size="14" color="#fff" />
              </view>
            </picker>
            <image style="width:20px;height: 20px;"
              src="https://cxj.szzkba.cn/upload/i/2024/02/29/112949_8.png">
            </image>
          </div>
        </nut-form-item> -->
        <nut-form-item label="店内分类" required>
          <div class="flex-a flex-b">
            <picker mode="selector" :range="selector" @change="onChange" style="width: 100%;">
              <view class="picker">
                {{ selectorChecked }}
                <TriangleDown size="14" color="#fff" />
              </view>
            </picker>
            <image style="width:20px;height: 20px;" src="https://cxj.szzkba.cn/upload/i/2024/02/29/112949_8.png">
            </image>
          </div>
        </nut-form-item>
      </nut-form>
    </div>
    <div class="info">
      商品规格
    </div>
    <div class="spec">
      <div v-for="(item, index) in specList" :key="item.id">
        <nut-form>
          <nut-form-item label="规格名称" required>
            <div class="flex-a flex-b">
              <nut-input v-model="basicData.prodSpecInfoList[index].specName" class="nut-input-text"
                placeholder="请输入规格名称" type="text" />
            </div>
            <nut-button shape="square" plain type="primary" size="mini" class="close" @click="delSpec(index)"
              v-if="specList.length > 1">
              <template #icon>
                <img src="https://cxj.szzkba.cn/upload/i/2024/03/01/103417.png" />
              </template>
              移除
            </nut-button>
          </nut-form-item>
          <nut-form-item label="价格" required>
            <div class="flex-a flex-b">
              <nut-input v-model="basicData.prodSpecInfoList[index].specSellingPrice" class="nut-input-text"
                placeholder="请输入价格" type="text" />
              <span>元</span>
            </div>
          </nut-form-item>
          <nut-form-item label="原价">
            <div class="flex-a flex-b">
              <nut-input v-model="basicData.prodSpecInfoList[index].spec_price" class="nut-input-text"
                placeholder="请输入原价" type="text" />
              <span>元</span>
            </div>
          </nut-form-item>
          <nut-form-item label="餐盒费">
            <div class="flex-a flex-b">
              <nut-input v-model="basicData.prodSpecInfoList[index].specOriginalPrice" class="nut-input-text"
                placeholder="请输入餐盒费" type="text" />
              <span>元</span>
            </div>
          </nut-form-item>
          <nut-form-item label="当前库存">
            <div class="flex-a flex-b">
              <nut-input v-model="basicData.prodSpecInfoList[index].stockNum" class="nut-input-text"
                placeholder="请输入当前库存" type="text" />
              <!-- <div class="stock">
                <text>沽清</text>
                <text>置满</text>
              </div> -->
            </div>
          </nut-form-item>
          <!-- <nut-form-item label="最大库存">
            <nut-input v-model="basicData.prodSpecInfoList[index].price" class="nut-input-text" placeholder="请输入最大库存"
              type="text" />
          </nut-form-item> -->
        </nut-form>
      </div>
    </div>
    <div class="add" @click="addSpec">
      <text>+</text>添加多规格
    </div>
    <div class="btn flex-a">
      <div>取消</div>
      <div @click="save">保存</div>
    </div>
  </div>
</template>

<script>
import Taro, { useRouter } from '@tarojs/taro';
import { reactive, toRefs, onMounted } from 'vue';
import { addGoods, getGoodsDetail, updateGoods, getClass } from '../../../api/index'
import { RectRight, CircleClose, CheckDisabled } from '@nutui/icons-vue-taro';
import { uploadUrl } from '../../../utils/index.js'
export default {
  name: 'eidt',
  components: {
    RectRight,
    CircleClose,
    CheckDisabled,
  },
  setup() {
    const state = reactive({
      uploadUrl: uploadUrl,
      defaultFileList: [
        // {
        // name: '1.png',
        // status: 'success',
        // message: '上传成功',
        // type: 'image',
        // url: 'https://cxj.szzkba.cn/up/uploadPath/2024/02/29/Oc2Ol2xUkcgu638f7f8b74da7374add87b40b6ca4786_20240229093711A001.jpg'
        // }
      ],
      specList: [{}],
      classList: [],
      basicData: {
        url: [],
        prodSpecInfoList: [
          {
            specSellingPrice: '',
          }
        ]
      },
      selector: [''],
      selectorChecked: '请选择分类',
      type: '',
      id: '',
    });
    onMounted(() => {
      getClass().then(res => {
        if (res.code == 200) {
          state.classList = res.data
          let arr = res.data, list = []
          arr.forEach(item => {
            list.push(item.name)
          })
          state.selector = list
        }
      })
      const router = useRouter();
      if (router.params.type) {
        state.type = router.params.type
        if (router.params.type == 'edit') {
          Taro.setNavigationBarTitle({
            title: '编辑商品'
          })
        } else {
          Taro.setNavigationBarTitle({
            title: '新增商品'
          })
        }
      }
      if (router.params.id) {
        state.id = router.params.id
        getGoodsDetail(router.params.id).then(res => {
          if (res.code == 200) {
            state.basicData = res.data
            let arr = []
            res.data.prodSpecInfoList.forEach(item => {
              arr.push({})
            })
            let list = state.classList
            if (list) {
              list.forEach(item => {
                if (item.id == res.data.sedCate) {
                  state.selectorChecked = item.name
                }
              })
            }
            state.specList = arr
            let urls = res.data.url, fileList = []
            urls.forEach(item => {
              fileList.push({
                name: '',
                url: item,
                status: 'success',
                message: '上传成功',
                type: 'image',
              })
            })
            state.defaultFileList = fileList
          }
        })
      }

    });
    const picSucc = (data, option, fileItem) => {
      let list = state.basicData.url, fileList = state.defaultFileList
      // state.basicData.url = JSON.parse(data.data.data).url
      list.push(JSON.parse(data.data.data).url + '')
      // fileList.push({
      //   url: JSON.parse(data.data.data).url + '',
      //   name: '',
      //   status: 'success',
      //   message: '上传成功',
      //   type: 'image',
      // })
      state.basicData.url = list
      // state.defaultFileList = fileList
      // console.log(data, option, fileItem)
    }
    const picDel = (files, fileList, index) => {
      state.basicData.url.splice(index, 1)
    }
    const onChange = (e) => {
      state.selectorChecked = state.selector[e.detail.value]
    }
    const addSpec = () => {
      state.specList.push({})
      state.basicData.prodSpecInfoList.push({})
    }
    const delSpec = (index) => {
      if (state.specList.length > 1) {
        state.specList.splice(index, 1)
        state.basicData.prodSpecInfoList.splice(index, 1)
      }
    }
    const save = () => {
      let arr = state.classList
      arr.forEach(item => {
        if (item.name == state.selectorChecked) {
          state.basicData.sedCate = item.id
        }
      })
      // let list = state.defaultFileList, urls = []
      // console.log(state.defaultFileList)
      // list.forEach(item => {
      //   urls.push(item.url)
      // })
      // state.basicData.url = urls
      console.log(state.basicData.url.length)
      var m = state.basicData.prodSpecInfoList.findIndex((value) => value.specName == '');
      var n = state.basicData.prodSpecInfoList.findIndex((value) => value.specSellingPrice == '');
      if (state.basicData.url.length <= 0) {
        showToast('请上传商品图片')
      } else if (!state.basicData.name) {
        showToast('请输入商品名称')
      } else if (!state.basicData.sedCate) {
        showToast('请选择分类')
      } else if (!state.basicData.sedCate) {
        showToast('请选择分类')
      } else if (m != -1) {
        showToast('请输入规格名称')
      } else if (n != -1) {
        showToast('请输入价格')
      } else {
        if (state.id) {
          updateGoods(state.basicData).then(res => {
            if (res.code == 200) {
              Taro.showToast({
                title: '编辑成功',
                icon: 'success',
                duration: 2000
              })
              Taro.reLaunch({
                url: '/packageA/pages/goods/index'
              })
            }
          })
        } else {
          addGoods(state.basicData).then(res => {
            if (res.code == 200) {
              Taro.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(() => {
                Taro.reLaunch({
                  url: '/packageA/pages/goods/index'
                })
              }, 500)
            }
          })
        }
      }
    }
    const showToast = (msg) => {
      Taro.showToast({
        title: msg,
        icon: 'error',
        duration: 2000
      })
    }
    return {
      ...toRefs(state), onChange, picSucc, addSpec, save, picDel, delSpec, showToast
    }
  }
}
</script>

<style lang="scss">
.edit {
  background: #F0F0F0;
  min-height: 100vh;

  .basic {
    .picker {
      color: #000;
    }
  }

  .info {
    padding: 20rpx 20rpx 10rpx;
    color: #747474;
    font-size: 26rpx;
  }

  .spec {
    .stock {
      white-space: nowrap;

      text {
        margin-left: 20rpx;
        color: #3A9AD3;
      }
    }

    .close {
      position: absolute;
      right: 10px;
      top: 20px;
      z-index: 999;

      img {
        width: 30px;
        height: 30px;
      }
    }
  }

  .add {
    padding: 20rpx;
    background: #fff;
    color: #1994DF;
    font-size: 32rpx;

    text {
      display: inline-block;
      width: 35rpx;
      height: 35rpx;
      text-align: center;
      line-height: 30rpx;
      border-radius: 50%;
      font-weight: bold;
      border: 4rpx solid #1994DF;
      margin-right: 10rpx;
    }
  }

  .btn {
    text-align: center;
    background: #fff;
    padding: 20rpx;
    width: 100%;
    margin: 20rpx 0;
    justify-content: center;

    div {
      color: #1994DF;
      width: 120rpx;
      height: 50rpx;
      text-align: center;
      line-height: 50rpx;
      border-radius: 5rpx;
      border: 2rpx solid #1994DF;
    }

    div:first-child {
      margin-right: 40rpx;
      color: #747474;
      border-color: #747474;
    }
  }
}
</style>
